package com.atguigu.dga.governance.assessor.calc;

import com.atguigu.dga.constant.DgaConstant;
import com.atguigu.dga.governance.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import com.atguigu.dga.util.SqlUtil;
import lombok.Getter;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

/**
 * @Description: Sql中是否包含select*指标
 * @Author: lay
 * @Date: 2024/6/30 19:14
 */
@Component("TABLE_SQL_SELECT_ALL")
public class TableSqlSelectAllAssessor extends Assessor {
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        //ods不跑任务，过滤掉
        if (assessParam.getTableMetaInfo().getTableMetaInfoExtra().getDwLevel().equals(DgaConstant.DW_LEVEL_ODS)){
            return;
        }
        //获取sql
        String taskSql = assessParam.getTDsTaskDefinition().getTaskSql();
        //解析sql
        SelectAllDispatcher selectAllDispatcher = new SelectAllDispatcher();
        SqlUtil.parseSql(taskSql, selectAllDispatcher);

        //判断是否包含select *
        if (selectAllDispatcher.getIsContainsSelectAll()){
            //给分
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            //问题项
            governanceAssessDetail.setAssessProblem("SQL中包含select*的操作");
            //考评备注
            governanceAssessDetail.setAssessComment("SQL为: " + taskSql );
        }
    }

    public static class SelectAllDispatcher implements Dispatcher {
        
        @Getter
        private Boolean isContainsSelectAll = false;

        /**
         * 每解析一个节点就执行一次此方法
         * @param node
         * @param stack
         * @param objects
         * @return
         * @throws SemanticException
         */
        @Override
        public Object dispatch(Node node, Stack<Node> stack, Object... objects) throws SemanticException {
            ASTNode astNode = (ASTNode) node;
            if (astNode.getType() == HiveParser.TOK_ALLCOLREF){
                isContainsSelectAll = true;
            }
            return null;
        }
    }
}
